package com.xique.door.wechat.service;

import cn.hutool.json.JSONUtil;
import com.xique.door.wechat.constant.WechatMsgTypeConstant;
import com.xique.door.wechat.util.WechatMessageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @program: xq-cloud
 * @ClassName WechatMessageService
 * @description:
 * @author: HdongSun
 * @create: 2022-10-26 15:39
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class WechatMessageService {

    private final TextReplyService textReplyService;

    private final SubscribeReplyService subscribeReplyService;

    /**
     * 微信回复
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    public String callback(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        try {
            Map<String, String> requestMap = WechatMessageUtil.parseXml(request);
            log.info("微信接收到消息:{}", JSONUtil.toJsonStr(requestMap));
            // 消息类型
            String msgType = requestMap.get("MsgType");

            // 处理其他消息，暂时不做回复
            switch (msgType) {
                case WechatMsgTypeConstant.REQ_MESSAGE_TYPE_TEXT:
                    // 文本消息处理
                    return textReplyService.reply(requestMap);
                case WechatMsgTypeConstant.REQ_MESSAGE_TYPE_EVENT: {
                    // 事件类型
                    String eventType = requestMap.get("Event");
                    switch (eventType) {
                        case WechatMsgTypeConstant.EVENT_TYPE_SUBSCRIBE:
                            // 关注/取关消息处理
                            return subscribeReplyService.reply(requestMap);
                        default:
                            return "";
                    }
                }
                default:
                    return textReplyService.reply(requestMap);
            }
        } catch (Throwable e) {
            log.error("回复消息错误", e);
        }
        // 不做回复
        return null;
    }
}
